package com.lyf.common.utils;


import com.lyf.common.exception.ApiException;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;

import static com.lyf.common.api.ResultCode.DATE_PARSE_ERROR;

/**
 * @author lyf
 */
public class DateUtils {

    public static final String DEFAULT_DATETIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
    public final static String ZH_DATE_FORMAT ="yyyy年MM月dd日";
    public final static String ZH_DATE_FORMAT_1 ="yyyy年MM月";
    public static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd";
    public static final String DEFAULT_DATE_PATTERN_1 = "yyyyMMddHHmmss";
    public static final String DEFAULT_DATE_PATTERN_2 = "yyyy-MM-dd HH:mm";
    public static final long MILLIS_A_DAY = 86400000L;
    /**
     * 字符串转时间戳
     *
     * @param dateTime
     * @return
     */
    public static Long stringToLong(String dateTime) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern(DEFAULT_DATETIME_PATTERN);
        LocalDateTime yy = LocalDateTime.parse(dateTime, df);
        return LocalDateTime.from(yy).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
    }

    public static Long stringToLong(String dateTime, String parttern) {
        SimpleDateFormat ft = new SimpleDateFormat(parttern);
        Date parse;
        try {
            parse = ft.parse(dateTime);
        } catch (ParseException e) {
            throw new ApiException(DATE_PARSE_ERROR);
        }
        return parse.getTime();
    }
    public static Date stringToDate(String dateTime, String parttern) {
        SimpleDateFormat ft = new SimpleDateFormat(parttern);
        Date parse;
        try {
            parse = ft.parse(dateTime);
        } catch (ParseException e) {
            throw new ApiException(DATE_PARSE_ERROR);
        }
        return parse;
    }
    public static String dateFormat(Date date, String parttern) {
        SimpleDateFormat ft = new SimpleDateFormat(parttern);
        return ft.format(date);
    }
    public static String zhDateFormat(LocalDate date, String parttern) {
        DateTimeFormatter zhDateFormat = DateTimeFormatter.ofPattern(parttern);
        return date.format(zhDateFormat);
    }
    public static LocalDateTime longToDateTime(long time) {
        LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(time), ZoneId.systemDefault());
        return localDateTime;
    }

    public static long dateTimeToLong(LocalDateTime time) {
        long longTime = time.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
        return longTime;
    }
}
